package net.maps;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import net.slavics.images.Images;
import net.slavics.maps.impl.LineGeoTransfer;
import net.slavics.maps.impl.Maps;
import org.apache.log4j.Logger;

/**
 *
 * @author slavic01
 * @version $Revision: 22 $
 * $LastChangedDate: 2008-05-05 19:27:06 +0000 (Mon, 05 May 2008) $ $Author: pslavicek@seznam.cz $
 */
public class OldMaps extends Maps {

    private String path = "../temp/";
    private String name = "OldMaps";
    private static Logger _log = Logger.getLogger(OldMaps.class);
    private Point sektor;

    public OldMaps() {
        super(256, 256, -718000 * 2, 1038000 * 2, -719000 * 2, 1037000 * 2);
        this.geoTransfer = new Trans();
        path += name + "/";
        File dir = new File(path);
        dir.mkdirs();
    }

    @Override
    public String getName() {
        return name;
    }

    public BufferedImage getMap(Point sektor) {
        this.sektor = sektor;
        BufferedImage img = null;
        File file = new File(path + geoTransfer.getFile(sektor).getName());
        _log.debug(file.exists() + " " + file.getAbsolutePath());
        try {
            try {
                Thread.sleep(500);
                img = getImageFromFile(file);
            } catch (InterruptedException ex) {
                _log.warn(ex.getLocalizedMessage(), ex);
            }
        } catch (IOException ex1) {
            _log.warn(ex1.getLocalizedMessage());
            try {
                URL url = geoTransfer.getUrl(sektor);
                //url = new URL("=http");
                img = getImageFromUrl(url);
                savePicture(file, img);
                Images.setErrText(img, url.getQuery());
            } catch (IOException ex2) {
                _log.warn(ex2.getLocalizedMessage());
                img = Images.getTestImage(width, height);
                Images.setName(img, sektor.toString());
            }
        }
        //Images.setText(img, new String[]{"Mapa souřadnice [" + sektor.x + "," + sektor.y + "]"});
        return img;
    }

    public Point getSektor() {
        return sektor;
    }
}

class Trans extends LineGeoTransfer {

    Trans() {
        super(.5, 0, -.5, 0);
    }

    @Override
    public URL getUrl(Point sektor) throws MalformedURLException {
        //"http://amapy.atlas.cz/printmap.ashx?an=atlasof&sc=4000&cx=-718642&cy=-1037779&h=256&w=256")
        return new URL("http", "amapy.atlas.cz", String.format("/printmap.ashx?an=atlasof&sc=4000&cx=%d&cy=-%d&h=256&w=256", (int) (sektor.x * 128 - bx), (int) (sektor.y * 128 - by)));
    }
}
